package com.tutu.filter;

import com.tutu.common.logger.Logger;
import com.tutu.controller.CommonsController;
import com.tutu.core.Constant;
import com.tutu.entity.vo.BaseCodeVo;
import com.tutu.utils.BaseUtil;
import com.tutu.utils.ImageUtils;
import com.tutu.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 公共过滤器
 */
@Slf4j
public class BackendFilter implements Filter {

    private static String[] SKIP_URLS = new String[]{};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String urls = filterConfig.getInitParameter("skipUrls");

        if (BaseUtil.isNotBlank(urls)) {
            List<String> list = new ArrayList<>();

            for (String skipUrl : urls.split(","))
                if (BaseUtil.isNotBlank(skipUrl)) {
                    skipUrl = "^" + skipUrl.replaceAll("\\*", ".*") + "$";
                    list.add(skipUrl);
                }

            SKIP_URLS = list.toArray(SKIP_URLS);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String url = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();
        url = url.substring(contextPath.length());
        Logger.info(contextPath + ", " + url);

        // 如果是文件地址，则直接放行
        if (url.contains(ImageUtils.uploadPath) || url.contains("wechat") || checkUrl(url)) {
            chain.doFilter(request, response);
            return;
        }

        if (SKIP_URLS != null) for (String skipUrl : SKIP_URLS) {
            Pattern pattern = Pattern.compile(skipUrl, Pattern.DOTALL);
            Matcher matcher = pattern.matcher(url);
            if (matcher.find()) {
                chain.doFilter(request, response);
                return;
            }
        }

        if (url.contains("backend") || url.contains("common") || url.contains("log") || url.contains("Pwd")) {
            try {
                // 监测是否已经登陆
                if (null != WebUtil.getSysInfo(httpRequest, Constant.CURRENT_LOGIN_MASTER_ID)) {
                    chain.doFilter(request, response);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();

                log.info("登录信息失效，自动跳转到登录界面...");

                httpResponse.sendRedirect(contextPath + "/login");

                return;
            }

            String xRequested = httpRequest.getHeader("X-Requested-With");

            if (xRequested != null && xRequested.contains("XMLHttpRequest")) {
                httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                WebUtil.print(httpResponse, "重新登录！");
            } else {
                httpResponse.sendRedirect(contextPath + "/login");
            }
        } else {
            if (!url.contains("home")) {
                // 默认重定向到官网
                httpResponse.sendRedirect(contextPath + "/home");
            } else {
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {
    }

    boolean checkUrl(String url) {
        for (BaseCodeVo baseCodeVo : CommonsController.loginMenuList)
            if (baseCodeVo.getCode().endsWith(url)) return true;

        return false;
    }
}
